<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入部门名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标准年级" prop="standardGrade">
        <el-select v-model="queryParams.standardGrade" placeholder="请选择标准年级" clearable size="small">
          <el-option
            v-for="dict in standardGradeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入学年份" prop="registerYear">
        <el-input
          v-model="queryParams.registerYear"
          placeholder="请输入入学年份"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="次序值" prop="deptOrder">
        <el-input
          v-model="queryParams.deptOrder"
          placeholder="请输入次序值"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="父级id" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入父级id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd('4','1')"
          v-hasPermi="['jx:jxdept:add']"
        >新增校区</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="jxdeptList"
      row-key="id"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="部门名称" align="center" prop="name" />
      <el-table-column label="微信部门id" align="center" prop="wxDeptId" />
      <el-table-column label="标准年级" align="center" prop="standardGrade" :formatter="standardGradeFormat" />
      <el-table-column label="入学年份" align="center" prop="registerYear" />
      <el-table-column label="次序值" align="center" prop="deptOrder" />
      <el-table-column label="微信父级id" align="center" prop="wxParentId" />
      <el-table-column label="父级id" align="center" prop="parentId" />
      <el-table-column label="是否有效" align="center" prop="isActive" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-custom"
            @click="handleAddAdmin(scope.row)"
            v-hasPermi="['jx:jxdept:edit']"
          >维护人员</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd((scope.row.type-1), scope.row.id)"
            v-hasPermi="['jx:jxdept:edit']"
            v-if="scope.row.type!='1'"
          >新增{{scope.row.type=='4'?'学段':(scope.row.type=='3'?'年级':(scope.row.type=='2'?'班级':''))}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['jx:jxdept:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['jx:jxdept:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改家校部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="(form.type=='4'?'校区':(form.type=='3'?'学段':(form.type=='2'?'年级':'班级')))+'名称'" prop="name">
          <el-input v-model="form.name" :placeholder="'请输入'+(form.type=='4'?'校区':(form.type=='3'?'学段':(form.type=='2'?'年级':'班级')))+'名称'" />
        </el-form-item>
        <el-form-item label="标准年级" v-if="form.type=='2'">
          <el-select v-model="form.standardGrade" placeholder="请选择标准年级">
            <el-option
              v-for="dict in standardGradeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入学年份" prop="registerYear" v-if="form.type=='2'">
          <el-input v-model="form.registerYear" placeholder="请输入入学年份" />
        </el-form-item>
        <el-form-item label="次序值" prop="deptOrder">
          <el-input v-model="form.deptOrder" placeholder="请输入次序值" />
        </el-form-item>
        <el-form-item label="父级部门" prop="parentId">
          <treeselect v-model="form.parentId" :options="jxdeptOptions" :normalizer="normalizer" placeholder="请选择父级部门" disabled="disabled"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="设置管理人员" :visible.sync="adminOpen" width="500px" >
      <el-card class="box-card manager-card">
        <div slot="header" class="clearfix">
          <span>{{qywxDeptUserSelector.adminJxDept.type=='1'?'班主任':(qywxDeptUserSelector.adminJxDept.type=='2'?'年级负责人':(qywxDeptUserSelector.adminJxDept.type=='3'?'学段负责人':(qywxDeptUserSelector.adminJxDept.type=='4'?'校区负责人':'')))}}</span>
          <el-button type="text" @click="setAdminSelectorOpen(qywxDeptUserSelector.adminJxDept.type)">增加{{qywxDeptUserSelector.adminJxDept.type=='1'?'班主任':(qywxDeptUserSelector.adminJxDept.type=='2'?'年级负责人':(qywxDeptUserSelector.adminJxDept.type=='3'?'学段负责人':(qywxDeptUserSelector.adminJxDept.type=='4'?'校区负责人':'')))}}</el-button>
        </div>
        <div class="admin-item" v-if="item.isActive=='1'&&item.type!='4'" v-for="item in adminList">
          <div class="admin-label">{{item.userName}}</div>
          <div class="admin-type" v-if="item.type=='3'">
            <el-select placeholder="请选择科目" v-model="item.subject">
              <el-option
                v-for="dict in subjectOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
            <el-button type="text" icon="el-icon-close" circle @click="delAdminList(item)"></el-button>
          </div>
        </div>
      </el-card>
      <el-card class="box-card teacher-card" v-if="qywxDeptUserSelector.adminJxDept.type=='1'">
        <div slot="header" class="clearfix">
          <span>任课老师</span>
          <el-button type="text" @click="setAdminSelectorOpen()">增加任课老师</el-button>
        </div>
        <div class="admin-item" v-if="item.isActive=='1'&&item.type=='4'" v-for="item in adminList">
          <div class="admin-label">{{item.userName}}</div>
          <div class="admin-type">
            <el-select placeholder="请选择科目" v-model="item.subject">
              <el-option
                v-for="dict in subjectOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
            <el-button type="text" icon="el-icon-close" circle @click="delAdminList(item)"></el-button>
          </div>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdmin">确 定</el-button>
        <el-button @click="cancelAdmin">取 消</el-button>
      </div>
      <el-dialog class="admin-selector" title="请选择人员" :visible.sync="adminSelectorOpen" width="800" append-to-body>
        <qywx-dept-user-selector ref="userSelector" :selectedList="qywxDeptUserSelector.selectedList" @onSelectUser="setSelectedList" @onDelUser="delSelectedList"></qywx-dept-user-selector>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="setAdminList">确 定</el-button>
          <el-button @click="setAdminSelectorClose">取 消</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { listJxdept, getJxdept, delJxdept, addJxdept, updateJxdept, exportJxdept, editAdmins } from "@/api/jx/jxdept";
import { listJxdeptAdminList, addJxadmins } from "@/api/jx/jxdeptadmin";
import { listUser } from "@/api/system/user";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {Message} from "element-ui";

import QywxDeptUserSelector from "@/components/QywxDeptUserSelector"

export default {
  name: "Jxdept",
  components: { Treeselect, QywxDeptUserSelector },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 家校部门表格数据
      jxdeptList: [],
      // 家校部门树选项
      jxdeptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      adminOpen: false,
      adminSelectorOpen: false,
      // 标准年级字典
      standardGradeOptions: [],
      //科目
      subjectOptions:[],
      // 查询参数
      queryParams: {
        isActive: undefined,
        name: undefined,
        wxDeptId: undefined,
        standardGrade: undefined,
        registerYear: undefined,
        deptOrder: undefined,
        wxParentId: undefined,
        parentId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name:[
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        standardGrade:[
          { required: true, message: '请选择标准年级', trigger: 'blur' }
        ],
        registerYear:[
          { required: true, message: '请输入入学年份', trigger: 'blur' }
        ]

      },

      //企业微信人员选择框
      qywxDeptUserSelector:{
        adminJxDept:{},//记录操作中的部门类型
        adminType:"",//记录操作中的管理员类型
        selectedList:undefined
      },

      //家校部门管理员列表 用于穿梭表右侧
      adminList:[]
    };
  },
  created() {
    this.getList();
    this.getDicts("SYS_STANDARD_GRADE").then(response => {
      this.standardGradeOptions = response.data;
    });
    this.getDicts("SYS_JX_KM_TYPE").then(response => {
      this.subjectOptions = response.data;
    });
  },
  methods: {
    /** 查询家校部门列表 */
    getList() {
      this.loading = true;
      listJxdept(this.queryParams).then(response => {
        this.jxdeptList = this.handleTree(response.data, "wxDeptId", "wxParentId","children","1");
        this.loading = false;
      });
    },
    /** 转换家校部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
	/** 查询部门下拉树结构 */
    getTreeselect() {
      listJxdept().then(response => {
        this.jxdeptOptions = [];
        const data = { id: 1, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "wxDeptId", "wxParentId","children","1");
        this.jxdeptOptions.push(data);
      });
    },
    // 标准年级字典翻译
    standardGradeFormat(row, column) {
      return this.selectDictLabel(this.standardGradeOptions, row.standardGrade);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset(flag, parentId) {
      let that = this
      this.form = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateTime: undefined,
        updateBy: undefined,
        isActive: "1",
        lesseeId: undefined,
        name: undefined,
        wxDeptId: undefined,
        type: flag || undefined,
        standardGrade: undefined,
        registerYear: undefined,
        deptOrder: undefined,
        toWxTime: undefined,
        wxParentId: undefined,
        parentId: parentId || undefined
      };
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(type, parentId) {
      this.reset(type, parentId);
	    this.getTreeselect();
      this.open = true;
      this.title = "添加家校部门";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
	    this.getTreeselect();
      if (row != undefined) {
        this.form.parentId = row.id;
      }
      getJxdept(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改家校部门";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateJxdept(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addJxdept(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除家校部门编号为"' + row.id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delJxdept(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },

    /*获取部门负责人列表*/
    getAdminList(deptId){
      let that = this
      that.adminList = []
      listJxdeptAdminList({jxDeptId:deptId, pageNum:1, pageSize:10}).then(function(res){
        if(res.code==200){
          that.adminList = res.rows
        }
      })
    },
    //打开人员选择框
    setAdminSelectorOpen(adminJxDeptType){
      let that = this
      if(!adminJxDeptType){
        this.qywxDeptUserSelector.adminType = "4"
      }else if(adminJxDeptType == "4"){
        this.qywxDeptUserSelector.adminType = "1"
      }else if(adminJxDeptType == "3"){
        this.qywxDeptUserSelector.adminType = "5"
      }else if(adminJxDeptType == "2"){
        this.qywxDeptUserSelector.adminType = "2"
      }else if(adminJxDeptType == "1"){
        this.qywxDeptUserSelector.adminType = "3"
      }
      this.qywxDeptUserSelector.selectedList = [];
      for(let i of this.adminList){
        if(i.type == this.qywxDeptUserSelector.adminType && i.isActive == "1"){
          this.qywxDeptUserSelector.selectedList.push(i)
        }
      }
      this.adminSelectorOpen = true
      setTimeout(function(){
        that.$refs.userSelector.clearUserList()
      },10)
    },
    setAdminSelectorClose(){
      this.$refs.userSelector.clearUserList()
      this.adminSelectorOpen = false
    },
    setSelectedList(item, val){
      var findObj = this.qywxDeptUserSelector.selectedList.find(obj => (obj.userId == item.userId && obj.type == this.qywxDeptUserSelector.adminType))
      if(val){
        if(!findObj){
          item.isActive = '1'
          item.type = this.qywxDeptUserSelector.adminType
          item.jxDeptId = this.qywxDeptUserSelector.adminJxDept.id
          this.qywxDeptUserSelector.selectedList.push(item)
        }else if(findObj.isActive=='0'){
          findObj.isActive = '1'
        }
      }else{
        if(findObj){
          let index = this.qywxDeptUserSelector.selectedList.findIndex(obj => obj.userId == item.userId)
          this.qywxDeptUserSelector.selectedList.splice(index,1)
        }
      }
    },
    delSelectedList(item){
      let findIndex = this.qywxDeptUserSelector.selectedList.findIndex(obj => obj.userId == item.userId)
      if(findIndex>-1){
        this.qywxDeptUserSelector.selectedList.splice(findIndex,1)
      }
    },
    setAdminList(){
      for(let [index, elem] of this.adminList.entries()){
        if(elem.type == this.qywxDeptUserSelector.adminType && elem.isActive=="1"){
          let findObjIndex = this.qywxDeptUserSelector.selectedList.findIndex(obj => obj.userId == elem.userId)
          if(findObjIndex==-1){
            if(elem.id){
              elem.isActive = "0"
            }else{
              this.adminList.splice(index,1)
            }
          }
        }
      }
      for(let i of this.qywxDeptUserSelector.selectedList){
        let findObj = this.adminList.find(obj => (obj.userId == i.userId && obj.type == i.type))
        if(findObj){
          if(findObj.isActive!="1"){
            findObj.isActive = "1"
          }
        }else{
          this.adminList.push(i)
        }
      }
      this.adminSelectorOpen = false
    },

    delAdminList(item){
      let findIndex = this.adminList.findIndex(obj => obj.userId == item.userId && obj.type == item.type && obj.isActive=="1")
      if(findIndex!=-1){
        if(this.adminList[findIndex].id){
          this.adminList[findIndex].isActive = "0"
        }else{
          this.adminList.splice(findIndex,1)
        }
      }
    },
    handleAddAdmin(dept){
      let that = this
      that.adminOpen = true
      that.qywxDeptUserSelector.adminJxDept = dept
      that.getAdminList(dept.id)
    },
    submitAdmin(){
      let that = this
      let params = []
      for(let i of that.adminList){
        if((i.type=="3"||i.type=="4")&&!i.subject){
          Message({
            message: "请选择科目名",
            type: 'error'
          })
          return;
        }
        params.push({
          id:i.id,
          jxDeptId:i.jxDeptId,
          userId:i.userId,
          type:i.type,
          subject:i.subject,
          isActive:i.isActive
        })
      }
      editAdmins({nssJxDeptAdminList:params}).then(function (res) {
        that.adminOpen = false
        that.qywxDeptUserSelector.adminJxDept = {}
        that.adminList = []
      })
    },
    cancelAdmin(){
      this.adminOpen = false
      this.qywxDeptUserSelector.adminJxDept = {}
      this.adminList = []
    }
  }
};
</script>
<style scope>
  .admin-item{
    display: flex;
    align-items: center;
    justify-content: space-between;
    border: 1px solid rgb(220, 223, 230);
    border-radius: 4px;
    margin-bottom: 20px;
  }
  .admin-item .admin-label{
    display: inline-block;
    height: 36px;
    line-height: 36px;
    padding: 0 20px;
  }
  .admin-item .el-input__inner{
    border: none;
    text-align: right;
  }

  /*.admin-selector .el-dialog__body{
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
  }
  .admin-selector .selector-left{
    flex: 0.49;
  }
  .admin-selector .selector-right{
    flex: 0.49;
  }
  .admin-selector .dept-tree{
    width: 100%;
    border: 1px solid rgb(230, 235, 245);
    border-radius: 4px;
    height: 200px;
    margin-bottom: 20px;
  }
  .admin-selector .dept-tree .el-tree{
    border-radius: 4px;
    height: 100%;
    overflow: auto;
  }
  .admin-selector .dept-user{
    width: 100%;
    border: 1px solid rgb(230, 235, 245);
    border-radius: 4px;
    padding: 10px;
    height: 300px;
    overflow: auto;
  }
  .admin-selector .dept-user .el-checkbox{
    display: block;
    margin-bottom: 10px;
  }
  .admin-selector .selected-dept-user{
    width: 100%;
    border: 1px solid rgb(230, 235, 245);
    border-radius: 4px;
    padding: 10px;
    height: 520px;
    overflow: auto;
  }
  .admin-selector .selected-dept-user .selected-item{
    background-color: rgb(230, 235, 245);
    padding: 5px 10px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }*/
  .box-card{
    margin-bottom: 20px;
  }
  .box-card .el-card__header .clearfix{
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .box-card .el-card__header .clearfix:after{
    display: none;
  }
</style>
